;'use strict';

$(function () {

    /*
     * -------------------------------------------------------------------------
     * ORDER SUMMARY
     * -------------------------------------------------------------------------
     */

    let $switch = $('#order-summary__number-of-items');

    let $orderSummaryProducts = $('#order-summary__products');

    $switch.on('click', function () {
        $switch.toggleClass('hide-products');
        if ($switch.hasClass('hide-products')) {
            $orderSummaryProducts.slideUp();
        } else {
            $orderSummaryProducts.slideDown();
        }
    });

    /*
     * -------------------------------------------------------------------------
     * PAYMENT
     * -------------------------------------------------------------------------
     */

    let $addressLine2Label = $('[for="address-line-2"]').add('[for="billing-address-line-2"]');
    let $addressLine2 = $('#address-line-2').add('#billing-address-line-2');

    $addressLine2Label.on('click', function () {
        $addressLine2Label.toggleClass('opened');
        if ($addressLine2Label.hasClass('opened')) {
            $addressLine2.slideDown();
        } else {
            $addressLine2.slideUp();
        }
    });

    /*
     * -------------------------------------------------------------------------
     * STRIPE
     * -------------------------------------------------------------------------
     */

    // https://stripe.com/docs/stripe-js#elements

    let stripePkKey = 'pk_live_ZoIwF3UIlHM3RcQWldHJXhyc00yGWAAnX1';

    if (typeof AppStripe !== 'undefined') {
        stripePkKey = AppStripe.pkLive;
    }

    // Create a Stripe client.

    // Create an instance of Elements.

    // Custom styling can be passed to options when creating an Element.
    // (Note that this demo uses a wider set of styles than the guide below.)
    var style = {
        base: {
            // https://stripe.com/docs/stripe-js/reference#the-element-container
            color: '#32325d',
            lineHeight: '18px',
            fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
            fontSmoothing: 'antialiased',
            fontSize: '16px',
            '::placeholder': {
                color: '#aab7c4'
            }
        },
        invalid: {
            color: '#fa755a',
            iconColor: '#fa755a'
        }
    };

    $("#continue-to-payment-method").on('click', function (e) {
        e.preventDefault();
        handleShippingAddressFormSubmit(document.querySelector("#payment-form"));
    });

    var shippingConstraints = {
        fullname: {
            // Full name is required
            presence: true,
        },
        addressLine1: {
            // Address Line 1 is required
            presence: true,
        },
        zipCode: {
            // Zip code is required
            presence: true,
        },
        city: {
            // City is required
            presence: true,
        },
        country: {
            // Country is required
            presence: true,
        },
        email: {
            // Email is required
            presence: true,
            email: true
        }
    };

    function handleShippingAddressFormSubmit(form, input) {
        // validate the form against the constraints
        var errors = validate(form, shippingConstraints);
        // then we update the form to reflect the results
        showErrors(form, errors || {});
        if (!errors) {
            // 保存订单
            const data = $('#payment-form').serialize();
            console.log(data);
            $.post('/order/create', data, function(data) {
                if (data.id > 0) {
                    total_price = data.total_price;
                    order_id = data.order_sn;
                }
            })
            $("#paypal-button-container").show();
            $("#continue-to-payment-method").hide();
        }
    }

    // Shows the errors for a specific input
    function showErrorsForInput(input, errors) {
        // This is the root of the input
        var formGroup = closestParent(input.parentNode, "payment-group");
        // Find where the error messages will be insert into
        var messages = formGroup.querySelector(".messages");
        // First we remove any old messages and resets the classes
        resetFormGroup(formGroup);
        // If we have errors
        if (errors) {
            // we first mark the group has having errors
            formGroup.classList.add("has-error");
            // then we append all the errors
            _.each(errors, function (error) {
                addError(messages, error);
            });
        } else {
            // otherwise we simply mark it as success
            formGroup.classList.add("has-success");
        }
    }

    // Recusively finds the closest parent that has the specified class
    function closestParent(child, className) {
        if (!child || child == document) {
            return null;
        }
        if (child.classList.contains(className)) {
            return child;
        } else {
            return closestParent(child.parentNode, className);
        }
    }

    function resetFormGroup(formGroup) {
        // Remove the success and error classes
        formGroup.classList.remove("has-error");
        formGroup.classList.remove("has-success");
        // and remove any old messages
        _.each(formGroup.querySelectorAll(".help-block.error"), function (el) {
            el.parentNode.removeChild(el);
        });
    }

    // Adds the specified error with the following markup
    // <p class="help-block error">[message]</p>
    function addError(messages, error) {
        var block = document.createElement("p");
        block.classList.add("help-block");
        block.classList.add("error");
        block.innerText = error;
        messages.appendChild(block);
    }

    // Updates the inputs with the validation errors
    function showErrors(form, errors) {
        // We loop through all the inputs and show the errors for that input
        _.each(form.querySelectorAll("input[name], select[name]"), function (input) {
            // Since the errors can be null if no errors were found we need to handle
            // that
            showErrorsForInput(input, errors && errors[input.name]);
        });
    }

});
